<?php
// Server
class Server
{
    private $serv;
    private $pdo;

    public function __construct() {
        $this->serv = new swoole_server("0.0.0.0", 9501);
        $this->serv->set(array(
            'worker_num' => 8,
            'daemonize' => false,
            'max_request' => 10000,
            'dispatch_mode' => 2,
            'debug_mode'=> 1,
            'task_worker_num' => 8,
        ));

        $this->serv->on('Start', array($this, 'onStart'));
        $this->serv->on('WorkerStart', [$this, 'onWorkerStart']);
        $this->serv->on('Connect', array($this, 'onConnect'));
        $this->serv->on('Receive', array($this, 'onReceive'));
        $this->serv->on('Close', array($this, 'onClose'));

        $this->serv->on('Task', array($this, 'onTask'));
        $this->serv->on('Finish', array($this, 'onFinish'));

        $this->serv->start();
    }

    public function onStart($serv ) {
        echo "Start\n";
    }

    public function onWorkerStart($serv, $work_id){
        if($work_id >= $serv->setting['worker_num']){
            $this->pdo = new PDO(
                'mysql:host=116.62.51.218;dbname=db_mood_index',
                'root',
                '726Y*H2123!@#',
                [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8mb4';",
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_PERSISTENT => true]
            );
        }
    }

    public function onConnect( $serv, $fd, $from_id ) {
        echo "fd {$fd} connect\n";
        $serv->send( $fd, "Hello {$fd}!\n" );
    }

    public function onReceive($serv, $fd, $from_id, $data ) {
//        $sql = [
//            'sql' => "select nickName from `t_user` where `id` = ?",
//            'param'=>[
//                $data,
//            ],
//            'fd'=>$fd,
//        ];
//        $ssqqll[] = $sql;
//        $sql['param']=[1289];
//        $ssqqll[] = $sql;
//        var_dump($ssqqll);
//        $res = $serv->task($sql);
//        $result[] = json_decode($res[0], true);
//        $result[] = json_decode($res[1], true);
        $serv->send($fd, json_encode(['erererererer']));


    }

    public function onClose($serv, $fd, $from_id ) {
        echo "Client {$fd} close connection\n";
    }
    public function onTask($serv,$task_id, $from_id, $data){

//        $statement = $this->pdo->prepare($data['sql']);
//        $statement -> execute($data['param']);
//        $result = $statement->fetchAll(PDO::FETCH_ASSOC);
        sleep(5);
        $serv->send($data['fd'], 'aaaaaaaaaaaaaaaa');
        return json_encode([$data['fd'],'result']);
    }
    public function onFinish($serv, $task_id, $data){
        $data = json_decode($data, true);
        $serv->send($data[0], $data);
    }

}
// 启动服务器
$server = new Server();
